package homework.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;

/**
 * 当前类是一个线程类
 * 主要管理客户端Socket信息的接收，并在控制台输出
 */
public class ClientAccept implements Runnable {

    private Socket socket;

    private boolean b = true;

    public ClientAccept(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
        char[] c;
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            while (b) {
                inputStream = socket.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                c = new char[1024];
                reader.read(c);
                String line = new String(c).trim();
                if (line != null && line.length() > 0) {
                    System.out.println(line);
                }
            }
        } catch (SocketException e) {
            System.out.println("Socket已关闭");
        } catch (Exception e) {
            System.out.println("大异常");
        } finally {
            b = false;
            try {
                if (reader != null) reader.close();
                if (inputStream != null) inputStream.close();
                socket.close();
                sc.close();
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}

